import type { RouteLocationRaw, Router } from 'vue-router';

import { PageEnum } from '/@/enums/pageEnum';
import { isString } from '/@/utils/is';
import { computed, unref } from 'vue';

import { useRouter } from 'vue-router';
import { REDIRECT_NAME } from '/@/router/constant';

export type RouteLocationRawEx = Omit<RouteLocationRaw, 'path'> & {
  path: PageEnum | string;
  query?: Object;
};

function handleError(e: Error) {
  console.error(e);
}

// page switch
export function useGo(_router?: Router) {
  let router;
  if (!_router) {
    router = useRouter();
  }
  const { push, replace } = _router || router;
  function go(opt: PageEnum | RouteLocationRawEx | string = PageEnum.BASE_HOME, isReplace = false) {
    if (!opt) {
      return;
    }
    if (isString(opt)) {
      isReplace ? replace(opt).catch(handleError) : push(opt).catch(handleError);
    } else {
      const o = opt as RouteLocationRaw;
      isReplace ? replace(o).catch(handleError) : push(o).catch(handleError);
    }
  }
  return go;
}

/**
 * @description: redo current page
 */
export const useRedo = (_router?: Router) => {
  const { push, currentRoute } = _router || useRouter();
  
  function redo(): Promise<boolean> {
    return new Promise((resolve) => {
      // 获取当前路由信息
      const { query, params = {}, name, fullPath } = unref(currentRoute.value);
      
      console.log('useRedo: name=', name, 'fullPath=', fullPath, 'params=', params, 'query=', query);
      
      if (name === REDIRECT_NAME) {
        console.log('useRedo: 当前已经是重定向页面，不再重定向');
        resolve(false);
        return;
      }
      
      // 创建新的参数对象，避免修改原始对象
      const newParams = { ...params };
      
      if (name && Object.keys(params).length > 0) {
        newParams['_redirect_type'] = 'name';
        newParams['path'] = String(name);
      } else {
        newParams['_redirect_type'] = 'path';
        newParams['path'] = fullPath;
      }
      
      const { path, ...rest } = newParams;
      
      console.log('useRedo: 重定向到', REDIRECT_NAME, '参数:', { ...rest, path: encodeURIComponent(path as string) }, '查询:', query);
      
      // 执行重定向
      push({ 
        name: REDIRECT_NAME, 
        params: { ...rest, path: encodeURIComponent(path as string) }, 
        query 
      })
      .then(() => {
        console.log('useRedo: 重定向成功');
        resolve(true);
      })
      .catch((error) => {
        console.error('useRedo: 重定向失败', error);
        resolve(false);
      });
    });
  }
  return redo;
};

export function useQuery(_router?: Router) {
  let router;
  if (!_router) {
    router = useRouter();
  }
  const query = computed(() => {
    return unref(router.currentRoute).query;
  });
  return query;
}
